from django.shortcuts import render

# Create your views here.
from django.http import JsonResponse, HttpResponse
from message_model.models import MessageTemplet
from sms_rest.serializers import TemplateSerializer
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.views.decorators.csrf import csrf_exempt
import json
import requests
import re
import random
from dysms_python.demo_sms_send import send_sms
import uuid
from datetime import datetime
from message_backup.models import SendResult
from django.forms.models import model_to_dict
from BeeBos import settings
from django.core import serializers
@csrf_exempt
def templateManage(request):
    if request.method == 'GET':
        queryset = MessageTemplet.objects.filter(status=2).values('template_code','template','template_type')
        # data = {
        #     'result': [model_to_dict(item) for item in queryset]
        # }

        data = list(queryset[:])
        data=json.dumps(data)
        return JsonResponse({"templete_info":data})

    elif request.method == 'POST':
        # 验证码
        l = []
        for i in range(6):
            rand_num = random.randint(0, 9)
            l.append(str(rand_num))
        code = ''.join(l)

        phone_number = request.POST.get('phone_number')
        if (phone_number == None):
            return JsonResponse({ "Message": "phone_number is none"})
        phone = phone_number.split(',')
        for p in phone:
            # 正则手机校验
            phone_pat = re.compile('^((13[0-9])|(14[5,7,9])|(15[^4])|(18[0-9])|(17[0,1,3,5,6,7,8]))\\d{8}$')
            res = re.search(phone_pat, p)
            if res == None:
                return JsonResponse({"Message": "phone_number is illegal"})

        sign_name = request.POST.get('sign_name')
        if (sign_name == None):
            return JsonResponse({"Message": "sign_name is none"})
        sign_name_query = MessageTemplet.objects.filter(sign_name=sign_name)
        if (len(sign_name_query) == 0):
            return JsonResponse({ "Message": "sign_name is non-existent"})

        template_code = request.POST.get('template_code')
        if (template_code == None):
            return JsonResponse({ "Message": "template is none"})
        template_code_query = MessageTemplet.objects.filter(template_code=template_code)
        if (len(template_code_query) == 0):
            return JsonResponse({ "Message": "template is non-existents"})
        # resultJson = {'Message': 'OK', 'RequestId': 'EE13747F-7509-4157-939A-F82CE4DF50A3',
        #               'BizId': '642113333708761184^0', 'Code': 'OK'}

        template_type = request.POST.get('template_type')
        __business_id = uuid.uuid1()

        if(int(template_type)==1):  #验证码
            #resultJson = {'Message': 'OK', 'RequestId': 'EE13747F-7509-4157-939A-F82CE4DF50A3','BizId': '642113333708761184^0', 'Code': 'OK'}

            resultJson = json.loads(send_sms(__business_id, phone_number, sign_name, template_code, '{"code":"'+code+'"}'))
            resultJson['RandomCode'] = code
            saveSendResult(resultJson,template_code,sign_name,phone_number,len(phone))
            return JsonResponse(resultJson)
        elif(int(template_type)==2): #推广短信
            #resultJson = {'Message': 'OK', 'RequestId': 'EE13747F-7509-4157-939A-F82CE4DF50A3','BizId': '642113333708761184^0', 'Code': 'OK'}
            resultJson = json.loads(send_sms(__business_id, phone_number, sign_name, template_code, None))
            saveSendResult(resultJson, template_code, sign_name, phone_number, len(phone))
            return JsonResponse(resultJson)



def testPost(request):
    url = settings.templeteUrl
    data = {'phone_number': '18819470276', 'sign_name': '原昇科技', 'template_code': 'SMS_143860075','template_type':'1'}
    r = requests.post(url,data=data)
    return JsonResponse(r.json())

def saveSendResult(resultJson,template_code,sign_name,phone_number,phoneLen):
    sendResult = SendResult()
    sendResult.request_id = resultJson['RequestId']
    sendResult.message = resultJson['Message']
    sendResult.code = resultJson['Code']
    sendResult.biz_id = resultJson['BizId']
    sendResult.create_time = datetime.now()
    sendResult.template_code = template_code
    sendResult.template_id = MessageTemplet.objects.only('id').get(template_code=template_code)
    sendResult.sign_name = sign_name
    sendResult.template = MessageTemplet.objects.get(template_code=template_code).template
    sendResult.mobile_len = phoneLen
    sendResult.mobile = phone_number
    sendResult.companyinfo = "其他平台"
    SendResult.save(sendResult)




